import React, { useEffect, useRef, useState } from 'react';
import { Empty, Spin, FloatButton } from 'antd';
import { LoadingOutlined, DownOutlined, ReloadOutlined } from '@ant-design/icons';
import MessageBubble from '../MessageBubble';
import { Message } from '../../../stores/conversation.store';
import { useBreakpoint } from '../../../hooks/useBreakpoint';
import './style.css';

interface MessageListProps {
  messages: Message[];
  isGenerating: boolean;
  onLoadMore?: () => Promise<void>;
}

const MessageList: React.FC<MessageListProps> = ({ messages, isGenerating, onLoadMore }) => {
  const breakpoint = useBreakpoint();
  const isMobile = breakpoint === 'mobile';

  const messagesEndRef = useRef<HTMLDivElement>(null);
  const listRef = useRef<HTMLDivElement>(null);
  const [showScrollButton, setShowScrollButton] = useState(false);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [pullDistance, setPullDistance] = useState(0);
  const touchStartY = useRef(0);

  const scrollToBottom = (smooth = true) => {
    messagesEndRef.current?.scrollIntoView({ behavior: smooth ? 'smooth' : 'auto' });
  };

  // 检测是否应该显示滚动到底部按钮
  const handleScroll = () => {
    if (!listRef.current) return;

    const { scrollTop, scrollHeight, clientHeight } = listRef.current;
    const isNearBottom = scrollHeight - scrollTop - clientHeight < 200;
    setShowScrollButton(!isNearBottom && scrollTop > 300);
  };

  // 下拉刷新逻辑（仅移动端）
  const handleTouchStart = (e: React.TouchEvent) => {
    if (!isMobile || !listRef.current) return;

    const { scrollTop } = listRef.current;
    if (scrollTop === 0) {
      touchStartY.current = e.touches[0].clientY;
    }
  };

  const handleTouchMove = (e: React.TouchEvent) => {
    if (!isMobile || !listRef.current || isRefreshing) return;

    const { scrollTop } = listRef.current;
    if (scrollTop === 0 && touchStartY.current > 0) {
      const touchY = e.touches[0].clientY;
      const distance = touchY - touchStartY.current;

      if (distance > 0) {
        setPullDistance(Math.min(distance, 80));
      }
    }
  };

  const handleTouchEnd = async () => {
    if (!isMobile || pullDistance < 50) {
      setPullDistance(0);
      touchStartY.current = 0;
      return;
    }

    if (onLoadMore) {
      setIsRefreshing(true);
      try {
        await onLoadMore();
      } finally {
        setIsRefreshing(false);
        setPullDistance(0);
        touchStartY.current = 0;
      }
    } else {
      setPullDistance(0);
      touchStartY.current = 0;
    }
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  useEffect(() => {
    const list = listRef.current;
    if (list) {
      list.addEventListener('scroll', handleScroll);
      return () => list.removeEventListener('scroll', handleScroll);
    }
  }, []);

  if (messages.length === 0 && !isGenerating) {
    return (
      <div className="message-list-empty">
        <Empty
          description="开始对话，探索无限可能"
          image={Empty.PRESENTED_IMAGE_SIMPLE}
        />
      </div>
    );
  }

  return (
    <div
      className="message-list"
      ref={listRef}
      onTouchStart={handleTouchStart}
      onTouchMove={handleTouchMove}
      onTouchEnd={handleTouchEnd}
    >
      {/* 下拉刷新指示器（移动端） */}
      {isMobile && pullDistance > 0 && (
        <div
          className="pull-to-refresh-indicator"
          style={{
            height: pullDistance,
            opacity: pullDistance / 80
          }}
        >
          <ReloadOutlined
            spin={isRefreshing}
            style={{
              fontSize: '20px',
              transform: `rotate(${pullDistance * 3.6}deg)`
            }}
          />
          <span style={{ marginLeft: '8px', fontSize: '14px' }}>
            {isRefreshing ? '加载中...' : pullDistance > 50 ? '释放刷新' : '下拉刷新'}
          </span>
        </div>
      )}

      <div className="message-list-content">
        {messages.map((message) => (
          <MessageBubble
            key={message.id}
            message={message}
          />
        ))}

        {isGenerating && (
          <div className="message-generating">
            <Spin
              indicator={<LoadingOutlined style={{ fontSize: 24 }} spin />}
              tip="AI 正在思考..."
            />
          </div>
        )}

        <div ref={messagesEndRef} />
      </div>

      {/* 滚动到底部按钮 */}
      {showScrollButton && (
        <FloatButton
          icon={<DownOutlined />}
          type="primary"
          onClick={() => scrollToBottom()}
          className="scroll-to-bottom-button"
          style={{
            right: isMobile ? 16 : 24,
            bottom: isMobile ? 80 : 24,
            width: isMobile ? 56 : 40,
            height: isMobile ? 56 : 40,
          }}
        />
      )}
    </div>
  );
};

export default MessageList;